package com.fantasy.easy.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fantasy.easy.biz.domain.BizBase;
import com.fantasy.easy.biz.domain.BizCredit;
import com.fantasy.easy.biz.domain.BizFeedback;
import com.fantasy.easy.biz.service.BizBaseService;
import com.fantasy.easy.biz.service.BizCreditService;
import com.fantasy.easy.biz.service.BizFeedbackService;
import com.fantasy.easy.biz.utils.ImageMarkUtils;
import com.fantasy.easy.core.util.SpringUtil;
import com.sun.jmx.snmp.Timestamp;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Description TODO
 * @Author sdehua-帅德华
 * @Email sdhstart@qq.com
 * @Date 2022/6/27 16:04
 * @Version 1.0
 **/
@RestController
@RequestMapping("/img")
public class CertifyImageController {

    @Resource
    BizBaseService bizBaseService;
    @Resource
    BizFeedbackService bizFeedbackService;
    @Resource
    BizCreditService bizCreditService;

    @GetMapping(value = "/certify", produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getImage() throws Exception {
        BufferedImage read = ImageIO.read(new FileInputStream(new File(System.getProperty("user.dir")+"/easy-sys/src/main/resources/img/certify-new.png")));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(read, "png", out);
        return out.toByteArray();
    }

    @PostMapping(value = "/certify")
    public int calImage(@RequestBody Map<String,String> map){
        String name = map.get("user");
        if (Strings.isBlank(name)){
            return 0;
        }
        BizBase base = new BizBase();
        base.setUname(name);
        BizBase bizBase = bizBaseService.getOne(new QueryWrapper<>(base));
        if (StringUtils.isEmpty(bizBase)){
            return 0;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Integer id = bizBase.getId();
        if (StringUtils.isEmpty(bizCreditService.getById(id).getCredit()) || StringUtils.isEmpty(bizFeedbackService.getById(id).getLevels())){
            return -1;
        }
        String date = format.format(new Date());
        if ("2".equals(map.get("type"))){
            BizCredit credit = bizCreditService.getById(id);
            ImageMarkUtils.createCreditImage(bizBase.getUname(),"20000"+id,date,credit.getCredit());
            return 1;
        }
        BizFeedback feedback = bizFeedbackService.getById(id);
        ImageMarkUtils.createCertifyImage(bizBase.getUname(),"10000"+id,date,feedback.getLevels().toString());
        return 1;
    }

}
